package com.example.springboot.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.example.springboot.entity.BlogCorrect;
import com.example.springboot.entity.User;
import com.example.springboot.entity.vo.BlogCorrectVO;
import com.example.springboot.entity.vo.CorrectNumVo;
import com.example.springboot.mapper.BlogCorrectMapper;
import com.example.springboot.mapper.CorrectNumMapper;
import com.example.springboot.service.BlogCorrectService;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BlogCorrectServiceImpl implements BlogCorrectService {
    @Autowired
    private BlogCorrectMapper blogCorrectMapper;
    @Autowired
    private CorrectNumMapper correctNumMapper;
    @Autowired
    private UserService userService;

    @Override
    public void insert(BlogCorrect blogCorrect) {
        blogCorrectMapper.insert(blogCorrect);
        Integer postId = blogCorrect.getPostId();
        String textId = blogCorrect.getTextId();
        Integer currentCorrectNum = correctNumMapper.getCorrectNum(postId, textId);
        System.out.println(currentCorrectNum);
        if (currentCorrectNum == null) {
            // 如果记录不存在，插入新记录并设为 1
            correctNumMapper.insertCorrectNum(postId, textId);
        } else {
            // 如果记录存在，直接加 1
            correctNumMapper.incrementCorrectNum(postId, textId);
        }
    }

    @Override
    public List<BlogCorrectVO> findList(Integer pageNum, Integer pageSize, Integer postId, String textId) {
        int offset = (pageNum - 1) * pageSize;
        List<BlogCorrect> blogCorrects = blogCorrectMapper.findList(offset, pageSize, postId, textId);
        List<BlogCorrectVO> blogCorrectVOList = new ArrayList<>();
        for (BlogCorrect blogCorrect : blogCorrects) {
            User user = userService.getUserById(blogCorrect.getAuthorId());
            BlogCorrectVO blogCorrectVO = new BlogCorrectVO();
            BeanUtil.copyProperties(blogCorrect, blogCorrectVO);
            blogCorrectVO.setNickname(user.getNickname());
            blogCorrectVO.setAvatar(user.getAvatar());
            blogCorrectVOList.add(blogCorrectVO);
        }
        return blogCorrectVOList;
    }

    @Override
    public List<Map<String, Integer>> getCorrectNum(Integer postId) {
        List<CorrectNumVo> correctNumVos = correctNumMapper.getCorrectNum2(postId);
        List<Map<String, Integer>> res = new ArrayList<>();
        for (CorrectNumVo correctNumVo : correctNumVos) {
            Map<String, Integer> map = new HashMap<>();
            map.put(correctNumVo.getTextId(), correctNumVo.getCorrectNum());
            res.add(map);
        }
        return res;
    }
}
